package com.bjtu.literatureclient.controller;


import com.bjtu.literatureclient.domain.user.User;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/** 
* @version:
* @Description: 项目总控制器
* @date: 2020年2月4日 下午3:31:57 
*/
@Controller
public class ProjectController {
	private final static Logger logger = LoggerFactory.getLogger(ProjectController.class);

	@Value("${spring.application.name}")
    private String appId;
    @Value("${eureka.instance.instance-id}")
    private String instanceId;
    @Value("${eureka.client.service-url.defaultZone}")
    private String serviceUrl;
    /* 
    * (Sikai Lin: 2020年2月4日)
    * @Description: 控制项目启动默认打开的第一个页面
    * @return
    */
    @RequestMapping("/")
    public String controller(){
        return "forward:/index.html";
    }


    @RequestMapping("/goToJournalAddPage")
    public String goToJournalAddPage(){
        return "forward:/miuser/journalAdd.html";
    }
    @RequestMapping("/goToJournal1AddPage")
    public String goToJournal1AddPage(){
        return "forward:/miuser/journalAdd1.html";
    }
    @RequestMapping("/goToChineseJournalsPage")
    public String goToChineseJournalsPage(){
        return "forward:/miuser/Chinesejournals.html";
    }
    @RequestMapping("/goToEnglishJournalsPage")
    public String goToEnglishJournalsPage(){
        return "forward:/miuser/Englishjournals.html";
    }
    @RequestMapping("/goToPlayGroundPage")
    public String goToPlayGroundPage(){
        return "forward:/miuser/playground.html";
    }
    
    @RequestMapping(value = "queryAuth")
    @ResponseBody
    public List<String> queryAuth(HttpServletRequest request) {
        logger.info("query user auth------------");
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        List<String> roleList=new ArrayList<String>();
        if(user.getUserRole().equals("0")){
            roleList.add("superAdmin");
        }else if(user.getUserRole().equals("1")){
            roleList.add("singleAdmin");
        }else if(user.getUserRole().equals("2")){
            roleList.add("teamAdmin");
        }else if(user.getUserRole().equals("3")){
            roleList.add("superUser");
        }else if(user.getUserRole().equals("4")){
            roleList.add("highUser");
        }else if(user.getUserRole().equals("5")){
            roleList.add("middleUser");
        }else if(user.getUserRole().equals("6")){
            roleList.add("primaryUser");
        }
        for (String string : roleList) {
        	logger.info("role:"+string);
		}
        return roleList;
    }

    @RequestMapping("/searchByAppId")
    @ResponseBody
    public String searchByAppId() throws IOException {
        URL restURL =new URL(serviceUrl+"apps/"+appId+"/"+instanceId);
        HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(30000);    //30秒连接超时
        conn.setReadTimeout(30000);       //30秒读取超时
        try {
            conn.connect();
            int code = conn.getResponseCode();
            conn.disconnect();
            System.out.println(code);
            if (code == 200) {
                return "success";
            }
        } catch (IOException e) {
            return "failed";
        }

        //关闭连接
        return null;
    }
    @RequestMapping("/registerEureka")
    @ResponseBody
    public String registerEureka() throws IOException {
        //String url = URLEncoder.encode("http://192.168.0.103:9998/eureka/apps/literatureclient","UTF-8");
        URL restURL =new URL(serviceUrl+"apps/"+appId);
        HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept","application/json");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("charset", "UTF-8");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setConnectTimeout(30000);    //30秒连接超时
        conn.setReadTimeout(30000);       //30秒读取超时
        String json =jsonParameter();
        conn.setRequestProperty("Content-Length", String.valueOf(json.length()));
        try {
            conn.connect();
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.write(json.getBytes());
            out.flush();
            out.close();
            int code = conn.getResponseCode();
            conn.disconnect();
            System.out.println(code);
            if (code == 204) {
                return "success";
            }
        } catch (IOException e) {
            return null;
        }
        return  null;
    }

    private String jsonParameter(){
        String jsonStr = "";
        try {
            InputStream path = this.getClass().getResourceAsStream("/register.json");
            BufferedReader reader = new BufferedReader(new InputStreamReader(path));
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}